package com.toymate.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

/**
 * FFmpegUtils
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class FFmpegUtils {

    public static void waveMaker(String sourcePath, String targetPath) {
        Runtime run = null;
        Process p = null;
        try {
            run = Runtime.getRuntime();
            //-ac 1:声道数量转成1  -ar 22050:采样率转成22050Hz  -ab 64k:比特率转成64kb
            //格式通过targetPath后缀自动识别转换
            String command = "ffmpeg -i " + sourcePath + " -ac 1 -ar 16000 -ab 64k " + targetPath;
            if (StringUtils.isBlank(command)) {
                return;
            }
            p = run.exec(command);
            p.waitFor();
            log.info("sourcePath:{} convert to targetPath:{} success", sourcePath, targetPath);
        } catch (Exception e) {
            log.error("msg=waveMaker异常：{}", e.getMessage(), e);
        } finally {
            try {
                p.getOutputStream().close();
                p.getInputStream().close();
                p.getErrorStream().close();
                run.freeMemory();
            } catch (IOException e) {
                log.error("msg=waveMaker异常：{}", e.getMessage(), e);
            }
        }
    }

}
